<template>
  <div>
    <div class="card" style="padding: 15px">
      您好，{{ user?.name }}！欢迎使用本系统
    </div>

    <div style="display: flex; margin: 10px 0">
      <!-- 左侧公告列表 -->
<!--      <div style="width: 50%;" class="card">-->
<!--        <div style="margin-bottom: 30px; font-size: 20px; font-weight: bold">公告列表</div>-->
<!--        <div>-->
<!--          <el-timeline reverse slot="reference">-->
<!--            <el-timeline-item v-for="item in notices" :key="item.id" :timestamp="item.time">-->
<!--              <el-popover-->
<!--                  placement="right"-->
<!--                  width="200"-->
<!--                  trigger="hover"-->
<!--                  :content="item.content">-->
<!--                <span slot="reference">{{ item.title }}</span>-->
<!--              </el-popover>-->
<!--            </el-timeline-item>-->
<!--          </el-timeline>-->
<!--        </div>-->
<!--      </div>-->

      <!-- 右侧图表 -->
      <div style="width: 100%;" class="card">
        <div ref="chart" style="width: 100%; height: 400px;"></div>
        <div style="margin-top: 20px; font-size: 14px; color: #666">
          数据说明：蓝色柱为总博客数，橙色柱为新增数量
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script>
import Footer from "@/components/Footer.vue";
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

// 注册ECharts组件
echarts.use([BarChart, CanvasRenderer]);

export default {
  name: 'Home',
  components: {
    Footer
  },
  data() {
    return {
      user: JSON.parse(localStorage.getItem('weblog') || '{}'),
      notices: [],
      systemData: [],
      chartInstance: null
    }
  },
  created() {
    this.$request.get('/notice/selectAll').then(res => {
      this.notices = res.data || [];
    });

    this.$request.get('/system/data').then(async res => {
      this.systemData = res?.data || [];
      //this.systemData = this.systemData.reverse()
      console.log('systemData', this.systemData)
      this.initChart(); // 数据加载后初始化图表
    });
  },
  mounted() {
    // 窗口大小变化时重置图表尺寸
    window.addEventListener('resize', () => {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    });
  },
  beforeDestroy() {
    // 组件销毁时清理图表实例
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
  },
  methods: {
    // 初始化图表
    initChart() {
      if (!this.systemData.length) return;

      const chartDom = this.$refs.chart;
      this.chartInstance = echarts.init(chartDom);

      // 处理时间格式
      const formattedData = this.systemData.map(item => ({
        time: this.formatTime(item.time),
        blogTotal: item.blogTotal,
        addBlogNumber: item.addBlogNumber
      }));

      // 按时间排序（示例数据已经是倒序）
      formattedData.sort((a, b) => new Date(a.time) - new Date(b.time));

      // 图表配置
      const option = {
        title: {
          text: '博客数据趋势分析',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            labelStyle: {
              backgroundColor: '#fff'
            }
          }
        },
        legend: {
          data: ['总博客数', '新增数量'],
          right: 20,
          top: 20
        },
        xAxis: {
          type: 'category',
          data: formattedData.map(item => item.time),
          axisLabel: {
            rotate: 45,
            fontSize: 12,
            color: '#666'
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 1000,
          axisLabel: {
            fontSize: 12,
            color: '#666'
          }
        },
        series: [
          {
            name: '总博客数',
            type: 'bar',
            data: formattedData.map(item => item.blogTotal),
            barWidth: '30%',
            color: '#2196F3'
          },
          {
            name: '新增数量',
            type: 'bar',
            data: formattedData.map(item => item.addBlogNumber),
            barWidth: '30%',
            color: '#FF9800'
          }
        ]
      };

      this.chartInstance.setOption(option);
    },

    // 时间格式转换
    formatTime(timeStr) {
      const date = new Date(timeStr);
      return `${date.getMonth() + 1}-${date.getDate()}`;
    }
  }
}
</script>

<style scoped>
.card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

/* 图表容器样式 */
#chart {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>